import React from 'react';
import { Icon, Modal, List, Button, ActivityIndicator, WingBlank } from 'antd-mobile';
import router from 'umi/router';
import 'antd-mobile/dist/antd-mobile.css';
import { MyIcon } from '../my-icon';
import styles from './index.less';
import { getSession, openUser } from '../../utils/utils'
import { FORM_TYPES } from '../envelope/form/form';
import { connect } from 'dva';
import { AUTHENTICATION_FAIL_CODE, E_TABBAR_DATA, P_TABBAR_DATA, ENTER_TYPE, PROCESS_STATUS } from '../../utils/Enum';
import { remoteLinkAddress } from '../../utils/ip'
import { Toast } from 'antd-mobile';
import infocircle from 'images/info-circle.svg'
import * as dd from 'dingtalk-jsapi';


const Item = List.Item
const { alert } = Modal;

@connect(({ sealAndSignatureModel, pdfModel, loading }) => ({
	sealAndSignatureModel,
	pdfModel,
	loadingIntendCertification: loading.effects['pdfModel/getIntendCertification'],
}))
class BaseLayout extends React.Component {

	constructor(props) {
		super(props);
		this.state = {
			isEditPagingSeal: false,
			visible: false,
			popType: '',
			sealPop: 'select',
			tabBarData: P_TABBAR_DATA,
			signInfo: null,
			sealLimit: 4,
			loading: true,
			defaultDealData: true, //判断是否是第一次请求的默认数据
			showPagingSeal: false,
			htmlType: true
		};
		this.scrollRef = React.createRef()
	}

	componentDidMount() {
		const { bindSignatureView } = this.props;
		if (bindSignatureView) {
			bindSignatureView(this);
		}
	}

	componentWillReceiveProps(nextProps) {
		let { tabBarData } = this.state;
		const { openTab } = nextProps;
		if (openTab !== 'WRITE_SIGN') {
			if (openTab !== '') {
				tabBarData.map((t, i) => {
					t.select = false;
					if (t.type === openTab) {
						tabBarData[i].select = true;
						if (nextProps.openTab !== this.props.openTab)
							this.requestData(openTab);
					}
				});
				this.setState({
					visible: true,
					popType: openTab,
					htmlType: true
				});
			}
		}
	}


	//滚动加载
	onSealScroll = () => {
		const { sealAndSignatureModel: { sealList, page } } = this.props;
		const { sealLimit } = this.state;
		const scrollDiv = this.scrollRef.current;
		if (scrollDiv) {
			const { clientWidth, scrollLeft, scrollWidth } = scrollDiv;
			if (clientWidth + parseInt(scrollLeft) == scrollWidth) {
				if (sealList.length < page.totalElements) {
					const { dispatch } = this.props;
					let offset = sealList.length;
					dispatch({
						type: 'sealAndSignatureModel/getSealList',
						payload: {
							enterprise_wsid: localStorage.getItem('enterpriseWsid'),
							limit: sealLimit,
							offset: offset,
						}
					})
				}
			}
		}
	}

	//防抖
	debounce(func, wait, immediate) {

		var timeout, result;

		var debounced = function () {
			var context = this;
			var args = arguments;

			if (timeout) clearTimeout(timeout);
			if (immediate) {
				// 如果已经执行过，不再执行
				var callNow = !timeout;
				timeout = setTimeout(function () {
					timeout = null;
				}, wait)
				if (callNow) result = func.apply(context, args)
			}
			else {
				timeout = setTimeout(function () {
					func.apply(context, args)
				}, wait);
			}
			return result;
		};

		debounced.cancel = function () {
			clearTimeout(timeout);
			timeout = null;
		};

		return debounced;
	}

	//关闭弹出层
	onClose = () => {
		this.setState({
			visible: false,
		});
		this.props.clearOpenTab();
	};

	onClosePagingSealModal = () => {
		this.setState({
			showPagingSeal: false,
		});
	}

	goConnect = () => {//跳转联系人
		// router.push(`/PersonalCertification?url=/Signature&type=${AUTHENTICATION_FAIL_CODE.PUSR}`);
		//取消对钉钉头部返回的控制
		if (dd.env.platform !== "notInDingTalk") {
			dd.biz.navigation.setLeft({
				control: false,//是否控制点击事件，true 控制，false 不控制， 默认false
				android: true, // 安卓端如果需要控制左上角返回事件加上这个字段，并设置为true
				text: '',//控制显示文本，空字符串表示显示默认文本
				onSuccess: function (result) {
				},
				onFail: function (err) { }
			});
			const { pdfModel: { enterpriseData } } = this.props;
			if (localStorage.getItem('orgSupUserAdminUserId') && enterpriseData.authorCropid) {
				const { authorCropid } = enterpriseData
				openUser(localStorage.getItem('orgSupUserAdminUserId'), authorCropid, 'profile')
				return
			}

		}
		window.location.href = 'https://www.yuque.com/docs/share/5afbd16f-5d96-48e0-a35e-9cddf928e3f6?#'
	}

	showAddPermission = () => {
		const { pdfModel: { useSeal, addSeal, authorName }, sealAndSignatureModel: { sealList } } = this.props;
		console.log(useSeal, addSeal, sealList)
		//如果能添加印章 就能使用印章
		if(addSeal) return true
		//如果能使用印章
		if(useSeal) {
			//如果能使用印章 但是印章数量为0, 提示需要管理员授权
			if(sealList.length === 0) {
				alert('提示',
					<div>
						<div>没有印章添加权限</div>
						<div>请联系<span style={{ color: '#108ee9' }} onClick={this.goConnect}>{authorName}</span>授权</div>
					</div>,
					[{
						text: '确定', onPress: () => { },
					}]
				)
				return false
			} else {
				//如果能使用印章 印章数量不为0
				return true
			}
		}
		//如果不能添加也不能使用
		alert('提示',
			<div>
				<div>没有印章添加权限</div>
				<div>请联系<span style={{ color: '#108ee9' }} onClick={this.goConnect}>{authorName}</span>授权</div>
			</div>,
			[{
				text: '确定', onPress: () => { },
			}]
		)
		return false
	}

	//点击显示弹出层
	/**
	 * @param e{type}
	 */
	showPopup = async (e, index) => {
		const { closeDrawer, getUserData, certificationStatus } = this.props;
		const { sealAndSignatureModel: { sealList } } = this.props;
		const { tabBarData } = this.state;
		// if(!certificationStatus){
		//   // getUserData();
		//   return
		// }
		if (closeDrawer) {
			const data = {
				openDrawer: false,
				leftIcon: 'flex'
			}
			closeDrawer(data)
		}

		await this.requestData(e)
		await this.changeSealStatus(e)
		tabBarData.map((t, i) => {
			t.select = false;
			if (i === index) {
				tabBarData[i].select = true;
			}
		});
		const { loading } = this.state;

		this.setState({
			tabBarData
		})
	};

	changeSealStatus = (e) => {
		switch (e) {
			case 'SEAL_SIGN':
			case 'MULTI_CHECK_MARK':
				const { sealAndSignatureModel: { sealList } } = this.props;
				const { loading } = this.state
				//先判断是不是有权限添加印章
				let status = this.showAddPermission()
				if (status && !loading) {
					this.setState({
						visible: true,
						popType: e,
						htmlType: true,
					});
				}
				break
			default:
				this.setState({
					visible: true,
					popType: e,
					htmlType: true,
				});
				break;
		}
	}

	//数据请求
	requestData = async (type) => {
		const { defaultDealData } = this.state;
		switch (type) {
			case 'WRITE_SIGN':
				await this.getSignatureListData();
				break;
			case 'SEAL_SIGN':
			case 'MULTI_CHECK_MARK':
				if (defaultDealData) {
					await this.getSealListData();
				}
				break;
			default:
				break;
		}
	}

	//选择印章
	getSelectSeal = (type) => {
		const { sealAndSignatureModel: { sealList }, pdfModel: { addSeal } } = this.props;
		const { loading } = this.state;
		const baseURL = remoteLinkAddress() + 'file';
		const sessionWsid = getSession();
		return (
			<List renderHeader={() => <div>选择印章</div>} className={styles.selectSeal}>
				<div className={styles.seals}>
					{
						addSeal ?
						<div className={styles.sealAdd}><div className={styles.signatureBtn}><Icon onClick={this.showAddSeal} type='cross' className={styles.addIcon} style={{ height: "30px", width: '30px' }} /></div><p>添加印章</p></div>
						:
						null
					}
					<div ref={this.scrollRef} className={styles.seal} onScroll={this.debounce(this.onSealScroll, 1000, false)}>
						{!loading ?
							sealList.map((i, index) => (
								<div key={index} className={styles.sealList}>
									<img src={baseURL + i.link.href + '?X-Requested-Session=' + sessionWsid} onClick={this.handleSealClick.bind(this, i, type)} />
									<p>{i.name}</p>
								</div>
							))
							: ''}
					</div>
				</div>

			</List>
		);
	};

	//添加印章
	getAddSeal = (popType) => {
		const { pdfModel: { enterpriseObj: { enterpriseAccountAuthentication: { enterprise: { unifiedSocialCreditCode } } } } } = this.props
		const addSealData = [{
			title: '上传印模图片',
			url: '/uploadImg',
			img: require('../../assets/shangchuan.png'),
			desc: '从手机相册或拍照上传印章图片',
			params: {}
		}, {
			title: '使用印模库',
			url: '/ImpressionLibrary',
			img: require('../../assets/yinmoku.png'),
			desc: '从系统印模库中选择一个模板添加',
			params: {
				unifiedSocialCreditCode
			}
		}]
		const { loading } = this.state;
		const Item = List.Item;
		const Brief = Item.Brief;
		return (
			<List renderHeader='添加印章' className={styles.addSeal}>
				<div className={styles.minHeight}>
					{!loading ?
						addSealData.map((item, index) => {
							return (
								<Item
									key={index}
									arrow="horizontal"
									thumb={item.img}
									multipleLine
									onClick={this.showModalAndSave.bind(this, item.url, popType, item.params)}
									className='addSealList'>

									<div className={styles.itemTitle}>
										{item.title}<Brief>{item.desc}</Brief>
									</div>
								</Item>
							);

						}) : ''}
				</div>
			</List>
		);

	};

	openSignaturePad = () => {
		const { openSignaturePad } = this.props;
		if (openSignaturePad) {
			openSignaturePad({ signaturePadIsOpen: true })
		}
		this.setState({
			visible: false,
		})
	}

	//签字
	getSignatureDetail = () => {
		const baseURL = remoteLinkAddress() + 'file';
		const url = '/signatureDetail';
		let { signInfo, loading } = this.state;
		if (!signInfo) {
			return (
				<List renderHeader='我的签名'>
					<List.Item className={styles.signature + " " + styles.minHeight + " " + styles.mySign}>
						{!loading ?
							<div className={styles.signature}>
								<div className={styles.signatureBtn} onClick={this.openSignaturePad}>
									<Icon type='cross' className={styles.addIcon} />
									<p>添加签名</p>
								</div>
							</div>
							: ''
						}
					</List.Item>
				</List>
			);
		} else {
			const { link: { href } } = signInfo;
			const sessionWsid = getSession();
			const src = baseURL + href + '?X-Requested-Session=' + sessionWsid;
			return (<List renderHeader='我的签名'>
				<List.Item className={'writer' + " " + styles.signature + " " + styles.minHeight + " " + styles.mySign}>
					{!loading ?
						<div className={styles.signatureCard}>
							<div className={styles.card}>
								<div className={styles.signImgDiv} onClick={this.handleWriteClick.bind(this, signInfo, 'WRITE_SIGN')}>
									<img src={src} />
								</div>
								<Icon type='cross-circle-o' className={styles.deleteSignature} onClick={this.deleteSignature} />
							</div>
						</div>
						: ''
					}
				</List.Item>
			</List>);
		}
	};

	//删除签名
	deleteSignature = () => {
		const { editing, dispatch } = this.props;
		this.setState({
			signInfo: null,
		});
		const { sealAndSignatureModel: { signatureList } } = this.props;
		const { personSealWsid } = signatureList[signatureList.length - 1];
		dispatch({
			type: 'sealAndSignatureModel/delSignatureDelete',
			payload: {
				wsid_signature: personSealWsid
			}
		})
	};

	//保存印章
	showModalAndSave = (e, popType, params) => {
		// const {pdfModel:{possess,authorName}}=this.props;
		this.setState({
			// visible: false,
			showPagingSeal: false,
		})
		// if(possess){
		this.onClose();
		alert('提示', '即将离开当前页，离开前保存您的最新操作', [//
			{
				text: '确定', onPress: () => {
					// Toast.loading('提交中...')
					this.goNext(e, popType, params)
				},
			},
		]);
		return
	}
	//页面跳转
	goNext = (e, popType, params) => {
		const { onSave } = this.props;
		let url = e + '?enterType=' + ENTER_TYPE.INTERIOR + '&popType=' + popType;
		for(let i in params) {
			url += `&${i}=${params[i]}`
		}
		// router.push(url);
		onSave('saveAndLeave', '', '', url)

	}



	//提交
	onSubmit = (e) => {
		const { showCertification, showModal, onClickSubmit, certificationStatus } = this.props;
		const { pdfModel: { processStatus } } = this.props
		switch (processStatus) {
			case PROCESS_STATUS.EUSR_AUTHORIZING_ERROR:
			case PROCESS_STATUS.EUSR_AUTHORIZED_ERROR:
				showModal()
				break;
			default:
				showCertification()
				break;
		}
		// if(!certificationStatus){
		//   let type=showModal()
		//   console.log('type'+type)
		//   if(type===1){
		//     showCertification();
		//   }
		//   return
		// }
		// if(onClickSubmit){
		//   console.log(346534)
		//   onClickSubmit();
		// }
	}

	//印章点击事件
	handleSealClick = (signInfo, type) => {
		const {
			pdfModel: { pdfList },
		} = this.props;
		if (type === FORM_TYPES.PAGING_SEAL) {
			if (pdfList.length === 1 && pdfList[0].totalPage != 1) {
				this.props.onChangeEditSealStatus(signInfo, type, pdfList[0].fileWsid);
				this.props.onEditPagingSeal(true);
				this.onClose();
				return;
			}
			if (pdfList.length === 1 && pdfList[0].totalPage == 1) {
				Modal.alert('', '文件只有一页，无需添加');
				this.onClose();
				return;
			}

			this.setState({
				showPagingSeal: true,
				signInfo,
			});
			this.onClose();
		} else {
			this.props.onChangeEditSealStatus(signInfo, type);
			this.onClose();
		}
	};

	handleWriteClick = (signInfo, type) => {
		//如果点击的是骑缝章
		if (type === FORM_TYPES.PAGING_SEAL) {
			this.props.onEditPagingSeal(true);
		}
		this.props.onChangeEditSealStatus(signInfo, type);
		this.onClose()
	};

	//获取一张签名
	getSignInfo = (signatureList) => {
		if (signatureList && signatureList[0]) {
			const signInfo = signatureList[signatureList.length - 1];
			this.setState({
				signInfo: signInfo,
				loading: false
			})
		} else {
			this.setState({
				loading: false
			})
		}
	};

	savePagingSeal = () => {
		this.props.savePagingSeal();
		this.props.onEditPagingSeal(false);
	};

	//请求签字列表数据
	getSignatureListData = () => {
		const { dispatch } = this.props;
		dispatch({
			type: 'sealAndSignatureModel/getSignatureList',
			payload: {
				author_wsid: localStorage.getItem('userWsid')
			},
			callback: (res) => {
				this.getSignInfo(res);
			},
		});
	}

	// 获取tabbar列表
	getTabBarList = () => {
		const { pdfModel: { userType } } = this.props;
		switch (userType) {
			case AUTHENTICATION_FAIL_CODE.EUSR:
				// 企业
				this.state.tabBarData = E_TABBAR_DATA;
				break;
			case AUTHENTICATION_FAIL_CODE.PUSR:
				// 个人
				this.state.tabBarData = P_TABBAR_DATA;
				break;
		}
	}

	// 请求公章列表数据
	getSealListData = async () => {
		const { dispatch } = this.props;
		const { sealLimit } = this.state
		await dispatch({
			type: 'sealAndSignatureModel/getSealList',
			payload: {
				enterprise_wsid: localStorage.getItem('enterpriseWsid'),
				limit: sealLimit,
			},
			callback: () => {
				this.setState({
					loading: false,
					defaultDealData: false
				})
			},
			refresh: true,
		})
	};

	//获取弹出框类型
	getPopType = () => {
		const { popType, loading } = this.state;
		let html = '';
		switch (popType) {
			case 'WRITE_SIGN':
				html = this.getSignatureDetail();
				break;
			case 'SEAL_SIGN':
			case 'MULTI_CHECK_MARK':
				const { sealAndSignatureModel: { sealList } } = this.props;
				if (sealList.length > 0 && !loading) {
					html = this.getSelectSeal(popType);

				} else {
					// let status= this.showAddPermission()
					//  if(status){
					html = this.getAddSeal(popType);
					// }

				}
				break;
			default:
				break;
		}

		return html;
	};

	showAddSeal = () => {
		let status = this.showAddPermission()
		if (status) {
			this.setState({
				htmlType: false
			});
			return
		}

		this.onClose()

	}


	pagingSealModalList = () => {
		const {
			pdfModel: { pdfList },
		} = this.props;
		return (
			<List
				renderHeader={
					<div className={styles.pagingSealModalListHeader}>
						<img src={infocircle} style={{ marginRight: '5px' }} />
            加盖骑缝章要求页数至少2页
          </div>
				}
				className="pagingSealModalList"
			>
				<div className={styles.pagingSealModalItems}>
					{pdfList.map(pdf => {
						let style = {};
						let disabled = false;
						if (pdf.totalPage == 1) {
							style = {
								color: '#bbb',
							};
							disabled = true;
						}
						return (
							<Item disabled={disabled}
								key={pdf.fileWsid}
								extra={
									<div className={styles.pagingSealModalListExtra} style={style}>
										共{pdf.totalPage}页
                        <Icon type="right" />
									</div>
								}
								className="pagingSealModalItem"
								onClick={() => disabled ? '' : this.onClickPagingSealListItem(pdf)}
							>
								{pdf.fileName}
							</Item>
						)
					})}
				</div>
			</List>
		);
	}

	onClickPagingSealListItem = (pdf) => {
		const { signInfo } = this.state;
		this.setState({
			showPagingSeal: false,
			signInfo: '',
		})
		this.props.onEditPagingSeal(true);
		this.props.onChangeEditSealStatus(signInfo, FORM_TYPES.PAGING_SEAL, pdf.fileWsid);
	}

	setstate = (params) => {
		const { popType } = params
		this.setState({ popType, visible: true, });
		this.requestData(popType);
	}

	render() {
		this.getTabBarList();
		const { visible, tabBarData, isEditPagingSeal, loading, showPagingSeal, htmlType, popType } = this.state;
		const { pdfModel: { userType, pdfList }, sealAndSignatureModel: { signatureList }, loadingAlipayPage } = this.props;
		const authentication = '/PersonalCertification';
		const tabWtd = userType == AUTHENTICATION_FAIL_CODE.EUSR ? styles.formsContainer_EUSE : styles.formsContainer_PUSE;
		const btn_radius = userType == AUTHENTICATION_FAIL_CODE.EUSR ? styles.submitBtn_EUSR : styles.submitBtn_PUSE;
		const pagingSealModalTitle = '选择一个文件盖骑缝章'
		return !this.props.isEditPagingSeal ? (
			<div className={styles.baseLayout}>
				<div className={styles.footerContainer}>
					<div className={styles.formsContainer + ' ' + tabWtd}>
						{tabBarData.map((item, index) => {
							return (
								<div
									className={item.select ? styles.formItem_select : styles.formItem}
									key={index}
									onClick={() => this.showPopup(item.type, index)}
								>
									<MyIcon type={item.icon} className={styles.icon} />
									<div className={styles.text}>{item.name}</div>
								</div>
							);
						})}
					</div>
					<div className={styles.submitContainer}>
						<Button
							className={styles.submitBtn + ' ' + btn_radius}
							type="primary"
							shape="round"
							// onClick={this.onSubmit.bind(this, authentication)}
							disabled={loadingAlipayPage}
							onClick={this.onSubmit}
						>
							提交
            </Button>
					</div>
				</div>
				<Modal
					popup
					visible={visible}
					onClose={this.onClose}
					animationType="slide-up"
					className={'pdfModal' + " " + styles.modal}
				>
					<div>
						{htmlType ? this.getPopType() : this.getAddSeal(popType)}
						<ActivityIndicator size="large" animating={loading} />
					</div>
					<div className={styles.cancelBtn} onClick={this.onClose}>
						取消
          </div>
				</Modal>
				<Modal
					popup
					visible={showPagingSeal}
					onClose={this.onClosePagingSealModal}
					animationType="slide-up"
					className={'pdfModal' + " " + styles.modal}
				>
					<div className={styles.pagingSealModalHeader}>{pagingSealModalTitle}</div>
					<div style={{ padding: '0 15px' }}>
						{this.pagingSealModalList()}
					</div>
					<div className={styles.cancelBtn} onClick={this.onClosePagingSealModal}>
						取消
          </div>
				</Modal>
			</div>
		) : (
				<div className={styles.baseLayout} style={{ display: 'flex' }}>
					<button className={styles.saveButton} onClick={this.savePagingSeal}>
						保存
        </button>
				</div>
			);
	}

}


export default BaseLayout;
